package com.zhuoyian.zyalibrary.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.content.Context;
import android.os.Environment;
import android.text.TextUtils;

public class DLUtil {

	public interface OnDownLoadListener {
		public void onChange(int filesize, int downfilesize);

		public void onDone(DownLoadState dlstate, String filepath,
				String downloadid);
	}

	public enum DownLoadState {
		/**
		 * 下载完成
		 */
		SUCCESS,
		/**
		 * 下载失败
		 */
		FAIL,
		/**
		 * 没有SDcard
		 */
		NOSDCARD,
		/**
		 * 没有参数
		 */
		NOPARA
	}

	private Context context;
	private String path;
	private int fileSize;
	private int downLoadFileSize;
	private boolean isStop;
	private String fileName;
	private String downloadId;
	private OnDownLoadListener onDownLoadListener;

	public OnDownLoadListener getOnDownLoadListener() {
		return onDownLoadListener;
	}

	public void setOnDownLoadListener(OnDownLoadListener onDownLoadListener) {
		this.onDownLoadListener = onDownLoadListener;
	}

	public String getDownloadId() {
		return downloadId;
	}

	public void setDownloadId(String downloadId) {
		this.downloadId = downloadId;
	}

	public DLUtil(String path, String fileName) {
		this.path = path;
		fileSize = 0;
		downLoadFileSize = 0;
		this.fileName = fileName;
		if (path == null || context == null)
			if (onDownLoadListener != null)
				onDownLoadListener.onDone(DownLoadState.NOPARA, null, null);
		// 如果没有SDCARD则不进行下载
		if (!android.os.Environment.getExternalStorageState().equals(
				android.os.Environment.MEDIA_MOUNTED)) {
			if (onDownLoadListener != null)
				onDownLoadListener.onDone(DownLoadState.NOSDCARD, null, null);
			return;
		}
		try {
			// 检测目录以及创建目录
			File file = new File(getDirPath());
			if (!file.exists()) {
				file.mkdirs();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 获取文件名
	 * 
	 * @return
	 */
	public String getFileName() {
		if (!TextUtils.isEmpty(fileName))
			return fileName;
		String filename = path.substring(path.lastIndexOf("/") + 1);
		filename = filename.substring(0, filename.lastIndexOf("."));
		return filename;
	}

	/**
	 * 获取后缀
	 * 
	 * @return
	 */
	public String getSufFix() {
		String suffix = path.substring(path.lastIndexOf("."));
		return suffix;
	}

	/**
	 * 获取文件下载目录
	 * 
	 * @return
	 */
	private String getDirPath() {
		return Environment.getExternalStorageDirectory().getAbsolutePath()
				+ "/download";
	}

	/**
	 * 获取下载的文件路径
	 * 
	 * @return
	 */
	public String getFilePath() {
		return getDirPath() + "/" + getFileName() + getSufFix();
	}

	/**
	 * 判断文件是否存在于本地
	 * 
	 * @return
	 */
	public boolean isFindLocal() {
		try {
			File file = new File(getFilePath());
			return file.exists();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	public void setStop(boolean isStop) {
		this.isStop = isStop;
	}

	/**
	 * 开启子线程下载文件
	 */
	public void start() {
		new Thread() {
			public void run() {
				try {
					HttpClient client = new DefaultHttpClient();
					HttpGet get = new HttpGet(path);
					HttpResponse response;

					response = client.execute(get);
					HttpEntity entity = response.getEntity();
					long length = entity.getContentLength();
					fileSize = (int) (length);
					InputStream is = entity.getContent();
					FileOutputStream fileOutputStream = null;
					if (is != null) {
						File file = new File(getDirPath(), getFileName()
								+ getSufFix());
						if (!file.exists()) {
							file.createNewFile();
						}
						fileOutputStream = new FileOutputStream(file);
						downLoadFileSize = 0;
						byte[] buf = new byte[1024];
						int ch = -1;
						if (onDownLoadListener != null)
							onDownLoadListener.onChange(fileSize,
									downLoadFileSize);
						while ((ch = is.read(buf)) != -1) {
							// 是否继续下载
							if (!isStop) {
								fileOutputStream.write(buf, 0, ch);
								downLoadFileSize += ch;
								if (length > 0) {
								}
								if (onDownLoadListener != null)
									onDownLoadListener.onChange(fileSize,
											downLoadFileSize);
							} else {
								break;
							}
						}
					}
					fileOutputStream.flush();
					if (fileOutputStream != null) {
						fileOutputStream.close();
					}
				} catch (ClientProtocolException e) {
					e.printStackTrace();
					isStop = true;
				} catch (IOException e) {
					e.printStackTrace();
					isStop = true;
				}
				//如果文件本身大小与下载的文件大小不相等时说明文件下载失败。
				if (fileSize != downLoadFileSize) {
					isStop = true;
				}
				if (onDownLoadListener != null) {
					DownLoadState dlstate = null;
					if (!isStop) {
						dlstate = DownLoadState.SUCCESS;
					} else {
						dlstate = DownLoadState.FAIL;
					}
					onDownLoadListener.onDone(dlstate, getFilePath(),
							getDownloadId());
				}
				if (isStop) {
					// 如果下载过程中由于网络中断或者手动终止下载则删掉未完成下载的文件（未下载好的文件无效）
					File file = new File(getDirPath(), getFileName()
							+ getSufFix());
					if (file.exists()) {
						file.delete();
					}
				}
			}
		}.start();
	}
}
